<template>
  <div class="setwrap scrolldiv">
    <div class="titlecommon">作物品种管理</div>
    <div class="panelben">
      <div class="titlecommon2">
        <span> 品种信息 </span>
        <!-- <div class="btn" @click="goMap">
          <el-icon><MapLocation /></el-icon>
          <span class="text text2"> 农场地图 </span>
        </div> -->
      </div>

      <div class="btntwo">
        <div class="btn btn2" @click="openAdd">
          <el-icon><Plus /></el-icon>
          <span class="text"> 新增 </span>
        </div>
        <div class="btn btn2 btn3" @click="openAddMore()">
          <el-icon><Plus /></el-icon>
          <span class="text"> 批量新增 </span>
        </div>
      </div>

      <div class="table">
        <el-table :data="tableData.value" style="width: 100%">
          <el-table-column prop="categoryName" label="作物种类" />
          <el-table-column prop="cropsSubclassName" label="作物品种名称" />
          <el-table-column prop="seedType" label="种子类别" />
          <el-table-column prop="licenceNumber" label="许可证编号" />
          <el-table-column prop="purity" label="纯度" />
          <el-table-column prop="neatness" label="净度" />
          <el-table-column prop="moisture" label="水分" />
          <el-table-column prop="germinationRate" label="发芽率" />
          <el-table-column prop="breedOrganization" label="育种单位"/>
          <el-table-column prop="warn" label="风险提示" key="slot">
            <template #default="scope">
              <el-tooltip
                :content="scope.row.warn"
                popper-class="box-itemdiy"
                placement="top"
              >
                <span>
                  {{scope.row.warn&&scope.row.warn.length>10?scope.row.warn.substr(0,10)+'……':scope.row.warn }}
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="plantArea" label="当前种植面积"/>
          <el-table-column prop="createTime" label="添加时间"/>
          <el-table-column prop="status" label="操作" key="slot">
            <template #default="scope">
              <div class="btnwrap">
                <div class="btntext" @click="openEdit(scope.row)">编辑</div>
                <div class="btntext delete" @click="delOne(scope.row)">
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="fy">
        <div class="total flexcenter">
          共 <span>{{ pageInfo.total }}</span
          >项数据
        </div>
        <el-pagination
          :currentPage="pageInfo.pageNum"
          @current-change="currentChange"
          background
          layout="prev, pager, next"
          :total="total"
        />
      </div>
    </div>

    <div class="panwrap">
      <div class="panelben panelben2">
        <div class="titlecommon2">
          <span> 种植作物品种统计 </span>

          <div class="dateDrop">
            <el-select
            @change="getPlantCountChange"
            v-model="chooseYear"
            class="m-2"
            placeholder="请选择"
            size="default"
          >
            <el-option
              v-for="item in yearOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          </div>
        </div>
        <div class="count">
          <div class="cone">
            <img src="@/assets/img/ff1.png" class="cicon" alt="" />
            种类:
            <span class="bold">
              {{ plantCount.value.categorySize }}
              </span
            >种
          </div>
          <div class="cone">
            <img src="@/assets/img/zl.png" class="cicon" alt="" />
            品种:
            <span class="bold">
              {{ plantCount.value.cropsSubclassSize }}
              </span
            >种
          </div>
          <div class="cone">
            <img src="@/assets/img/ff2.png" class="cicon" alt="" />
            面积:
            <span class="bold">
              {{ plantedTotal?plantedTotal.toFixed(0):'-' }}
              </span
            >亩
          </div>
        </div>
        <div class="table2">
          <el-table :data="tableData2.value" style="width: 100%">
            <el-table-column prop="gardenName" label="地块" />
            <el-table-column prop="categoryName" label="作物类型" />
            <el-table-column prop="cropsSubclassName" label="作物品种" />
            <el-table-column prop="area" label="种植面积(亩)" />
          </el-table>
          <div class="fy">
            <div class="total flexcenter">
              共 <span>{{ totalTable}}</span>项数据
            </div>
            <el-pagination background
              :currentPage="pageNum"
              :page-size="sizeset"
              @current-change="currentChange2"
            layout="prev, pager, next" :total="totalTable" />
          </div>
        </div>
      </div>
      <div class="panelben panelben3">
        <div class="titlecommon2">
          <span> 种植作物品种占比 </span>
          <!-- <div class="dateDrop">
            <el-dropdown>
              <span class="el-dropdown-link">
                2023
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>2023</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div> -->
        </div>
        <div class="rightpanel">
          <div v-if="nodataFlag" class="leftp leftpadd">
            暂无数据
          </div>
          <div class="leftp" v-if="!nodataFlag">
            <div class="totaltext">种植总面积</div>
            <div class="mu">
              <span class="bignum">{{ plantedTotal?plantedTotal.toFixed(0):'-' }}</span>
              亩
            </div>
          </div>
          <div class="centerp" v-if="!nodataFlag">
            <pieChartS :data="pieData.value"/>
          </div>
          <div class="rightp" v-if="!nodataFlag">
            <div class="rchild" v-for="(item, index) in pieArr.value" :key="index">
              <div class="color" :style="{ background: colorArr[index] }"></div>
              <div class="name">
                {{ item.categoryName }}
              </div>
              <div class="rtext1">
                <span class="smallnum">
                  {{ item.area?item.area.toFixed(0):'-' }}
                </span>
                <span class="small">亩</span>
              </div>
              <div class="rp">{{ item.plantRate }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="!editFlag ? '编辑作物种类品种' : '新增作物种类品种'"
      width="30%"
      custom-class="diyclass"
    >
      <div class="mcontent">
        <div class="mchild">
          <div class="label">作物种类:</div>
          <el-input
            :disabled="!editFlag"
            v-model="form.value.categoryName"
            placeholder="请输入"
            clearable
          />
        </div>
        <div class="mchild">
          <div class="label">作物品种名称:</div>
          <el-input
            :disabled="!editFlag"
            v-model="form.value.cropsSubclassName"
            placeholder="请输入"
            clearable
          />
        </div>
        <div class="mchild">
          <div class="label">种子类别:</div>
          <el-input
            v-model="form.value.seedType"
            placeholder="请输入"
            clearable
          />
        </div>
        <div class="mchild">
          <div class="label">许可证编号:</div>
          <el-input
            v-model="form.value.licenceNumber"
            placeholder="请输入"
            clearable
          />
        </div>
        <div class="mchild">
          <div class="label">纯度:</div>
          <div class="dydiv">
            <el-input
              type="number"
              v-model="form.value.purity"
              placeholder="请输入"
              clearable
            >
              <template #prepend>≥</template>
              <template #append>%</template>
            </el-input>
          </div>
        </div>
        <div class="mchild">
          <div class="label">净度:</div>
          <div class="dydiv">
            <el-input
              type="number"
              v-model="form.value.neatness"
              placeholder="请输入"
              clearable
            >
              <template #prepend>≥</template>
              <template #append>%</template>
            </el-input>
          </div>
        </div>
        <div class="mchild">
          <div class="label">水分:</div>
          <div class="dydiv">
            <el-input
              type="number"
              v-model="form.value.moisture"
              placeholder="请输入"
              clearable
            >
              <template #prepend>≥</template>
              <template #append>%</template>
            </el-input>
          </div>
        </div>
        <div class="mchild">
          <div class="label">发芽率:</div>
          <div class="dydiv">
            <el-input
              type="number"
              v-model="form.value.germinationRate"
              placeholder="请输入"
              clearable
            >
              <template #prepend>≥</template>
              <template #append>%</template>
            </el-input>
          </div>
        </div>
        <div class="mchild">
          <div class="label">育种单位:</div>
          <el-input
            v-model="form.value.breedOrganization"
            placeholder="请输入"
            clearable
          />
        </div>
        <div class="mchild">
          <div class="label">风险提示:</div>
          <el-input v-model="form.value.warn" placeholder="请输入" clearable />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button :disabled="!overFlag" @click="submit">提交</el-button>
          <el-button type="primary" @click="dialogVisible = false">
            取消
          </el-button>
        </span>
      </template>
    </el-dialog>
    <add-more ref="addmore" @refreshList="getList" type="plantType" />
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  reactive,
  onMounted,
  onUnmounted,
  computed,
} from "vue";
import pieChartS from "@/chart/pieChart/pie-singletwo";
import { useRouter } from "vue-router";
import addMore from "../plantingType/modal/addMore.vue";
import { post, get,deletePost } from "@/public/request/api";
import { ElMessage } from "element-plus";
import { ElMessageBox } from "element-plus";
import bus from "@/utils/bus";
import moment from "moment";
import storage from "@/store";
export default defineComponent({
  components: {
    pieChartS,
    addMore,
  },
  setup() {
    let editFlag = ref(false);
    let sizeset=ref(5)
    let overFlag = computed({
      get() {
        return (
          form.value.breedOrganization &&
          form.value.categoryName &&
          form.value.cropsSubclassName &&
          form.value.germinationRate &&
          form.value.licenceNumber &&
          form.value.moisture &&
          form.value.neatness &&
          form.value.purity &&
          form.value.seedType &&
          form.value.warn
        );
      },
      set(value) {},
    });
    //变量
    const userRole = storage.state.userRole;
    let dialogVisible = ref(false);
    let activeIndex = ref(0);
    let pageInfo = reactive({
      pageSize: 10,
      pageNum: 1,
      total: 0,
    });
    let chooseYear=moment().format("YYYY")
    const yearOptions = [
      {
        value:moment().subtract(2, "years").format("YYYY") ,
        label:moment().subtract(2, "years").format("YYYY") ,
      },
      {
        value: moment().subtract(1, "years").format("YYYY"),
        label: moment().subtract(1, "years").format("YYYY"),
      },
      {
        value: moment().format("YYYY"),
        label: moment().format("YYYY"),
      },
    ];
    let form = reactive({
      value: {
        breedOrganization: "",
        categoryName: "",
        cropsSubclassName: "",
        germinationRate: "",
        licenceNumber: "",
        moisture: "",
        neatness: "",
        purity: "",
        seedType: "",
        warn: "",
        id: "",
      },
    });
    const menu = ["摄像头", "虫情测报仪", "气象站", "土壤墒情仪", "水肥一体机"];
    const colorArr = [
      "rgba(114, 82, 204, 1)",
      "rgba(255,215,0, 1)",
      "rgba(34,139,34, 1)",
      "rgba(	0,206,209, 1)",
      "rgba(46, 229, 229, 1)",
    ];
    const pieArr=reactive({
      value:[]
    })
    const rate = ref([
      {
        tips: 48,
        colorData: {
          textStyle: "#fff",
          series: {
            color: ["rgba(255, 255, 255, 0.16)", "transparent"],
            dataColor: {
              normal: "#319AF5",
              shadowColor: "#97e2f5",
            },
          },
        },
      },
      {
        tips: 32,
        colorData: {
          textStyle: "#fff",
          series: {
            color: ["rgba(255, 255, 255, 0.16)", "transparent"],
            dataColor: {
              normal: "#456AE5",
              shadowColor: "#97e2f5",
            },
          },
        },
      },
      {
        tips: 20,
        colorData: {
          textStyle: "#fff",
          series: {
            color: ["rgba(255, 255, 255, 0.16)", "transparent"],
            dataColor: {
              normal: "#E58A2E",
              shadowColor: "#97e2f5",
            },
          },
        },
      },
    ]);
    let pieData=reactive({
      value:[]
    })
    const percents = ref([
      {
        name: "大豆",
        value: 25,
        count: "2586",
      },
      {
        name: "红薯",
        value: 35,
        count: "2586",
      },
      {
        name: "玉米",
        value: 55,
        count: "2586",
      },
      {
        name: "小麦",
        value: 45,
        count: "2586",
      },
    ]);
    const tableData2 = reactive({
      value:[]
    })
    let total = ref(0);
    let tableData = reactive({
      value: [],
    });
    let plantedTotal=ref(null)

    // 生命周期
    onMounted(() => {
      getList();
      getPlantCount()
      bus.on('changeBase',getPlantCount);
    });
    const router = useRouter();
    let realTableData2=reactive({
      value:[]
    })
    let plantCount=reactive({
      value:{
        categorySize:null,
        cropsSubclassSize:null,
      }
    })
    let nodataFlag=ref(false)
    let pageNum=ref(1)
    let totalTable=ref(0)
    onUnmounted(() => {
      bus.off('changeBase',getPlantCount);
    });

    //methods
    function goMap() {
      bus.emit("menuChange", 0);
      router.push({ path: "/farmlandData/statistics" });
    }
    function openAdd() {
      dialogVisible.value = true;
      editFlag.value = true;
      form.value = {
        breedOrganization: "",
        categoryName: "",
        cropsSubclassName: "",
        germinationRate: "",
        licenceNumber: "",
        moisture: "",
        neatness: "",
        purity: "",
        seedType: "",
        warn: "",
        id: "",
      };
    }
    function openAddMore() {
      this.$refs.addmore.dialogVisible = true;
    }
    function getPlantCount(){
      get("/plant/statistics", {
        selectedYear:chooseYear,
        //cropCategoryId:null,
      }).then(res=>{
        plantedTotal.value=res.data.plantedTotal
        pieArr.value=res.data.categoryProportions
        pieData.value=[]
        if(res.data.categoryProportions.length==0){
          nodataFlag.value=true
        }else{
          nodataFlag.value=false
        }
        res.data.categoryProportions.forEach((item,index)=>{
          pieData.value.push({
            value:item.area,
            name:item.categoryName,
            color:colorArr[index]
          })
        })
        console.log('pieData.value',pieData.value)
        
        realTableData2.value=JSON.parse(JSON.stringify(res.data.plantStatistics))
        tableData2.value=res.data.plantStatistics.slice((pageNum.value-1)*sizeset.value,sizeset.value)
        totalTable.value=realTableData2.value.length


        plantCount.value.categorySize=res.data.categorySize
        plantCount.value.cropsSubclassSize=res.data.cropsSubclassSize
      })
    }
    function delOne(id) {
      ElMessageBox.confirm("确认删除?")
        .then(() => {
          delHandel(id.id);
        })
        .catch(() => {
          // catch error
        });
    }
    function delHandel(id) {
      deletePost("/crops/del", {
        id
      }).then((res) => {
        ElMessage({
            message: "删除成功",
            type: "success",
        });
        getList()
      });
    }
   

    function getList() {
      get("/crops/page", {
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
      }).then((res) => {
        tableData.value = res.pageInfo.list;
        pageInfo.total = res.pageInfo.total;
        total.value = res.pageInfo.total;
      });
    }
    function openEdit(val) {
      console.log(val);
      editFlag.value = false;
      form.value=val
      dialogVisible.value = true;
    }
    function submit() {
      if (editFlag.value) {
        post("/crops/add", form.value).then((res) => {
          ElMessage({
            message: "新增成功",
            type: "success",
          });
          getList();
          dialogVisible.value = false;
        });
      } else {
        post("/crops/edit", form.value).then((res) => {
          ElMessage({
            message: "编辑成功",
            type: "success",
          });
          getList();
          dialogVisible.value = false;
        });
      }
    }
    function currentChange(e) {
      pageInfo.pageNum = e;
      getList();
    }
    function currentChange2(e) {
      pageNum.value=e
      let s=(pageNum.value-1)*sizeset.value
      let end=(pageNum.value)*sizeset.value
      tableData2.value=realTableData2.value.slice(s,end)
    }
    function getPlantCountChange(e){
      chooseYear=e
      getPlantCount()
    }
    // return
    return {
      userRole,
      nodataFlag,
      plantCount,
      getPlantCountChange,
      pieData,
      plantedTotal,
      yearOptions,
      chooseYear,
      getPlantCount,
      totalTable,
      delOne,
      currentChange,
      total,
      openEdit,
      sizeset,
      openAdd,
      editFlag,
      pageInfo,
      submit,
      getList,
      menu,
      activeIndex,
      tableData,
      tableData2,
      colorArr,
      pieArr,
      percents,
      rate,
      goMap,
      dialogVisible,
      form,
      openAddMore,
      overFlag,
      pageNum,
      currentChange2
      
    };
  },
});
</script>

<style lang="scss">
.box-itemdiy{
  max-width: 300px;
}

.setwrap {
  .el-input__wrapper{
    background: rgba(255, 255, 255, 0.08);
  }
  .el-table th.el-table__cell,
  .el-table .el-table__cell,
  .el-table tr,
  .el-table--fit {
    background: transparent !important;
    color: #fff !important;
  }
  .el-table th.el-table__cell.is-leaf,
  .el-table td.el-table__cell {
    border-bottom: 1px solid rgba(255, 255, 255, 0.08) !important;
  }
  .el-pagination.is-background .el-pager li {
    background: transparent !important;
    color: #fff !important;
  }
  .el-pagination.is-background .btn-next {
    background: none !important;
  }
  .btn-prev {
    background: none !important;
  }
}
.dydiv {
  .el-input__wrapper {
    border-radius: 0 !important;
  }
  .el-input-group__prepend,
  .el-input-group__append {
    background: rgba(255, 255, 255, 0.08) !important;
    border: none !important;
    box-shadow: none !important;
  }
  .el-input-group__prepend {
    border-top-left-radius: 100px;
    border-bottom-left-radius: 100px;
  }
  .el-input-group__append {
    border-top-right-radius: 100px;
    border-bottom-right-radius: 100px;
  }
}
</style>

<style lang="scss" scoped>
@import "@/assets/scss/index.scss";
.leftpadd{
  font-size: 20px;
  display: flex;
  justify-content: center!important;
  flex: 1;
}
.dydiv {
  display: flex;
  align-items: center;
  .dyfh {
    padding: 4px 10px;
  }
}
.rightpanel {
  .rp{
    width: 70px;
  }
  .name{
    width: 30px;
    margin-right: 10px!important;
  }
  .smallnum{
    width: 70px;
    
  }
  .rtext1{
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 110px;
    
  }
  .smallnum{
    text-align: right;
    margin-right: 6px;
  }
}
.setwrap {
  
  .panelben3 {
    //width: 32%;
    width: 600px;
    height: 370px;
    display: flex;
    flex-direction: column;
    .rightpanel{
      flex: 1;
    }
  }
  .centerp {
    // border: 1px solid rgba(255, 255, 255, 0.08);
    // border-radius: 1000px;
  }

  .panwrap {
    margin-top: 20px;
    align-items: flex-start!important;
  }
  .count {
    display: flex;
    align-items: center;
    margin-top: 20px;
    justify-content: space-between;
    .cone {
      margin-bottom: 10px;
      width: 32%;
      border-radius: 7px;
      background: rgba(255, 255, 255, 0.08);
      padding: 10px;
      display: flex;
      align-items: center;
      .cicon {
        width: 40px;
        margin: 0 10px;
      }
      .bold {
        font-size: 20px;
        font-weight: bold;
        position: relative;
        top: 2px;
        margin-right: 7px;
        left: 5px;
      }
    }
  }
  .videowrap {
    display: flex;
    align-items: center;
    margin-top: 20px;
    .videoc {
      width: 33.1%;
      margin-right: 2%;
      position: relative;
      border-radius: 10px;
      overflow: hidden;
      .fm {
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
      }
      .videoinfo {
        position: absolute;
        bottom: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.6);
        width: 100%;
        padding: 8px 13px;
        display: flex;
        align-items: center;
        .status {
          padding: 0 5px;
          border-radius: 5px;
          font-size: 10px;
          margin-left: 10px;
        }
        .status1 {
          color: rgba(8, 204, 126, 1);
          background: rgba(8, 204, 126, 0.18);
        }
      }
    }
  }
  .statusdiv {
    padding: 1px 5px;
    border-radius: 4px;
    font-size: 10px;
    width: 40px;
    box-sizing: border-box;
  }
  .statusdiv1 {
    color: rgba(8, 204, 126, 1);
    background-color: rgba(8, 204, 126, 0.18);
  }
  .btntext2 {
    margin-left: 10px;
  }
  .tabwrap {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;
    .search {
      display: flex;
      background: rgba(255, 255, 255, 0.08);
      border-radius: 100px;
      .sbtn {
        background: rgba(9, 127, 229, 1);
        border-radius: 100px;
        padding: 3px 15px;
        cursor: pointer;
      }
      .input {
        background: transparent;
        outline: none;
        padding-left: 10px;
        border-radius: 0;
        border: none;
        color: #fff;
      }
    }
  }
  .btn3 {
    width: 100px !important;
    margin-left: 10px;
  }
  .btntwo {
    display: flex;
    align-items: center;
  }
  .fy {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .total {
      color: rgba(255, 255, 255, 0.6);
      font-size: 10px;
      span {
        font-size: 20px;
      }
    }
  }
  .table {
    margin-top: 20px;
  }
  .btnwrap {
    display: flex;
    align-items: center;
    .btntext {
      color: rgba(49, 127, 245, 1);
      cursor: pointer;
    }
    .delete {
      color: rgba(245, 98, 98, 1) !important;
      margin-left: 15px;
    }
  }
  .titlecommon2 {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .btn2 {
    width: 70px;
    box-sizing: border-box;
    padding: 5px 10px !important;
    margin-top: 20px;
  }
  .btn {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: rgba(9, 127, 229, 1);
    font-size: 14px;
    padding: 5px 20px;
    border-radius: 5px;
    .text {
      position: relative;
      // top: 2px;
    }
    cursor: pointer;
    span.text2 {
      margin-left: 10px;
    }
  }
  .tab {
    display: flex;
    align-items: center;

    .tabchildActive {
      color: rgba(49, 154, 245, 1) !important;
      background: rgba(49, 154, 245, 0.16) !important;
    }
    .tabchild {
      cursor: pointer;
      padding: 4px 13px;
      border-radius: 100px;
      color: rgba(255, 255, 255, 0.6);
      background: rgba(255, 255, 255, 0.08);
      margin-right: 20px;
    }
  }
}
</style>
